<?php


class CMS_LoginCookie {

	private $cookie_hash_key = 'g506jekfJcpBvRFrpcuJeixezgPNyALmOt4_Ut0f3XE-';
  private $table   = 'cms_user';
  private $login   = ''; # cms login  
  private $cookename = 'cmscookie';
  private $persistent = 1;
	private $persistent_time=86400;
  
	#function __construct($login=''){
	#	$this->login = login;
  #}
  
	/** 創建用戶Session 與 Cookies
	* 原名: set_usercookies
	* @param Array $h_param	其他參數
	*    
	* @return boolean
	*    false: failed to set
	*/
	function set($h_user, $h_param=array()){
		#$login = $this->login;
		
#		$db = new DBI('read');
#		$dbh_r = $db->connect();
		
		if($h_user==null){
			return false;
		}	
			$persistent = isset($h_param['persistent']) ? $h_param['persistent'] : $this->persistent; //用是否記住登入，默認記住
				
#			if($logindata['persistent_time']!=255 && !empty($logindata['persistent_time'])){
#				$persistent_time = $logindata['persistent_time']*86400;
#			}else{
#				$persistent_time = 86400;
#			}

			$persistent_time = $this->persistent_time;
						
		  $sess = new Session();
			$sess->set('~CMS_logged-in',1);
			$sess->set('CMS_USERID',  $h_user['id']);
			$sess->set('CMS_LOGIN',   $h_user['login']);
			$sess->set('CMS_USERNAME',$h_user['name']);
			
			$sess->set('persistent',$persistent);			
			$usercookie = $h_user['id'].'|'.$h_user['login'].'|'.$h_user['name'].'|'.$this->salt(6);
			$usercookie = authcode($usercookie, 'ENCODE', $this->cookie_hash_key);

			if($persistent==1){
				setcookie($this->cookename, $usercookie,time()+$persistent_time);
			}
			return true;
		
	}
	
	
  function salt($length=6){
   $my_array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",  "m", "n", "p", "0", "1", "2", "3", "4", "5",'6','7','8','9','q','r','s','t','u','v','w','x','y','z');
   $temp= array_rand(array_flip($my_array), $length); 
   return implode('', $temp);
    #return  'x1234sod';
  }
	
	
	/** 清楚用戶Session 與 Cookies 
	 *  原名: unset_usercookies
	 */
	function clear(){
		$sess = new Session();
		$sess->set('~CMS_logged-in',0);
		$sess->set('CMS_USERID',  '');
	  $sess->set('CMS_LOGIN',   '');
		$sess->set('CMS_USERNAME','');
		
		#setcookie($this->cookename);
		unset($_COOKIE[$this->cookename]); 
    setcookie($this->cookename, NULL, -1); 
	}	

  /*
   * 原名: check_usercookies
   */
	function check(){
		$sess = new Session();
		if($sess->get('~CMS_logged-in')==0   && 
		   isset($_COOKIE[$this->cookename]) &&
		   $_COOKIE[$this->cookename]!=''        ){	// session 過期或丟失
			
			$usercookie = authcode($_COOKIE[$this->cookename],'DECODE',$this->cookie_hash_key);
			$a_user = explode('|', $usercookie);

		
			if(count($a_user)==4){
				$sess->set('~CMS_logged-in',1);
				$sess->set('CMS_USERID',  $a_user[0]);
				$sess->set('CMS_LOGIN',   $a_user[1]);
		    $sess->set('CMS_USERNAME',$a_user[2]);
				$sess->set('persistent',1);	//有cookies的用戶 persistent必定是1						
				return true;
			}
	
		}
		return false;
	}



}
?>